// menuStore.js  
import { defineStore } from 'pinia';
export const useMenuStore = defineStore('menu', {
    state: () => {
        const localData = localStorage.getItem('ak_gl');
        if (localData) {
            try {
                const parsedData = JSON.parse(localData);
                return parsedData;
            } catch (error) {
                console.error(error);
            }
        }
        return {
            isCollapse: false,
            selectMenu: [],
            routerList: [],
            menuActive: '1-1',
            menuPath: '/dashboard'
        };
    },
    actions: {
        //侧边栏展开控制
        collapseMenu() {
            this.isCollapse = !this.isCollapse;
        },
        //添加顶部菜单
        addMenu(payload) {
            if (!this.selectMenu.some(item => item.path === payload.path)) {
                this.selectMenu.push(payload);
            }
        },
        //关闭菜单
        closeMenu(payload) {
            const index = this.selectMenu.findIndex(val => val.name === payload.name);
            if (index !== -1) {
                this.selectMenu.splice(index, 1);
            }
        },
        //动态路由配置
        async dynamicMenu(payload) {
            //通过glob导入文件
            const modules = import.meta.glob('../views/**/**/*.vue')
            function routerSet(router) {
                //遍历数据
                router.forEach(route => {
                    if (!route.children) {
                        //获得url
                        const url = `../views${route.meta.path}/index.vue`
                        //通过url匹配包
                        route.component = modules[url]

                    } else {
                        //递归
                        routerSet(route.children)
                    }
                });
            }
            routerSet(payload)
            //拿到完整的路由数据
            this.routerList = payload
            // console.log(this.routerList)
        },
        //更新active
        updateMenuActive(payload) {
            this.menuActive = payload;
        },
        //更新选中数据
        updateMenuDate(payload) {
            this.menuPath = payload;
            // console.log(this.menuPath,'stor里面更新完menudate');
        }
    },
    // 开启数据缓存，根据持久化插件
    persist: {
        enabled: true,
        strategies: [
            {
                // 自定义名称
                key: 'ak_gl',
                // 保存位置
                storage: localStorage,
            }
        ],
    },
});